package com.ce.framework.util;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;



import com.ce.framework.exception.AppException;

public class Formater
{

    public static final String DATE_FROMATE_TYPE_DATE = "yyyy-MM-dd";

    public static final String DATE_FROMATE_TYPE_YEAR = "yyyy";

    public static final String DATE_FROMATE_TYPE_SECOND = "yyyy-MM-dd HH:mm:ss";


    public static String dateFormater(Date date) throws AppException {
        if (date == null)
        {
            return "";
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try
        {
            return df.format(date);
        } catch (Exception e)
        {
            e.printStackTrace();
            throw new AppException(e);
        }
    }


    public static String dateFormater(Date date, String typeStr)
            throws AppException {
        if (date == null)
        {
            return "";
        }
        SimpleDateFormat df = new SimpleDateFormat(typeStr);
        try
        {
            return df.format(date);
        } catch (Exception e)
        {
            e.printStackTrace();
            throw new AppException(e);
        }
    }


    public static long getTimeInMillis() {
        Calendar calendar = Calendar.getInstance();
        long time = calendar.getTimeInMillis();
        return time;
    }

    public static Date getDate() {
        Calendar calendar = Calendar.getInstance();
        return calendar.getTime();
    }


    public static Date toDate(String date) throws AppException {
        if (date == null)
        {
            return null;
        }
        SimpleDateFormat df = null;
        if (date.indexOf(":") != -1)
        {
            df = new SimpleDateFormat(Formater.DATE_FROMATE_TYPE_SECOND);
        } else
        {
            df = new SimpleDateFormat(Formater.DATE_FROMATE_TYPE_DATE);
        }
        try
        {
            return df.parse(date);
        } catch (Exception e)
        {
            e.printStackTrace();
            throw new AppException(e);
        }
    }


    public static String addDate(String dateStr, int days)
            throws AppException {
        SimpleDateFormat df = new SimpleDateFormat(
                Formater.DATE_FROMATE_TYPE_DATE);
        Calendar calendar = Calendar.getInstance();
        String result = null;
        try
        {
            Date dt = df.parse(dateStr);
            calendar.setTime(dt);
            calendar.add(Calendar.DATE, days);
            dt = calendar.getTime();
            result = df.format(dt);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return result == null ? "" : result;
    }


    public static String IsoToGB2312(String src) {
        String des = null;
        if (src == null)
            return "";
        try
        {
            byte[] temp = src.getBytes("ISO8859_1");
            des = new String(temp, "GB2312");
        } catch (Exception e)
        {
        	LogUtil.logInfo("-----------Error Formater.IsoToGB2312()!");
        }
        return des == null ? "" : des;
    }

    public static String IsoToUTF_16(String src) {
        String des = null;
        if (src == null)
            return "";
        try
        {
            byte[] temp = src.getBytes("ISO8859_1");
            des = new String(temp, "UTF-16");
        } catch (Exception e)
        {
        	LogUtil.logInfo("-----------Error Formater.UTF_16()!");
        }
        return des == null ? "" : des;
    }

    public static String GB2312ToIso(String src) {
        String des = null;
        if (src == null)
            return "";
        try
        {
            byte[] temp = src.getBytes("GB2312");
            des = new String(temp, "ISO8859_1");
        } catch (Exception e)
        {
        	LogUtil.logInfo("-----------Error Formater.GB2312ToIso!");
        }
        return des == null ? "" : des;
    }


    public final static String GBKToISO(String src) {
        try
        {
            if (src != null)
            {
                return new String(src.getBytes("GBK"), "ISO-8859-1");
            }
        } catch (Exception e)
        {
            System.out
                    .println("-----------Error com.it168.util.CharsetManager.GBKToISO()!");
        }
        return null;
    }


    public final static String[] GBKToISO(String[] src) {
        if (src.length != 0)
        {
            String[] tmp = new String[src.length];
            for (int i = 0; i < src.length; i++)
            {
                tmp[i] = GBKToISO(src[i]);
            }
            return tmp;
        }
        return null;
    }

    public static String trim(String str) {
        if (str == null)
        {
            return str;
        } else
        {
            return str.trim();
        }
    }

    public static boolean isEmptyString(String arg) {
        if (arg != null && arg.trim().length() > 0)
        {
            return false;
        }
        return true;
    }

    public static String caseStartChar(String arg) {
        if (!Formater.isEmptyString(arg))
        {
            return arg;
        }
        String strTmp = arg.substring(0, 1);
        strTmp = strTmp.toUpperCase();
        strTmp += arg.substring(1);
        return strTmp;
    }

    public static String moneyFormat(String money, int fractionDigits)
            throws AppException {
        if (Formater.isEmptyString(money))
        {
            return "";
        }
        int index = money.indexOf(".");
        if (index == -1)
        {
            index = money.length();
        }
        int index1 = index - fractionDigits;
        String strTmp = money;
        while (index1 > 0)
        {
            String prevValue = strTmp.substring(0, index1);
            strTmp = prevValue + "," + strTmp.substring(index1);
            index1 = index1 - fractionDigits;
        }
        return strTmp;
    }

    public static String moneyFormat(Double money, int fractionDigits)
            throws AppException {
        if (money == null)
        {
            throw new AppException("");
        }
        try
        {
            NumberFormat numberFormat = NumberFormat.getNumberInstance();
            numberFormat.setMaximumFractionDigits(fractionDigits);
            numberFormat.setMinimumFractionDigits(fractionDigits);
            return numberFormat.format(money);
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return null;
    }

    public static Double moneyParse(String money, int fractionDigits)
            throws AppException {
        if (money == null || money.trim().length() == 0)
        {
            throw new AppException("");
        }
        try
        {
            NumberFormat numberFormat = NumberFormat.getNumberInstance();
            numberFormat.setMaximumFractionDigits(fractionDigits);
            numberFormat.setMinimumFractionDigits(fractionDigits);
            Number num = numberFormat.parse(money.trim());
            double dnum = num.doubleValue();
            return new Double(dnum);
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return null;
    }

    public static String toMoneyFormat(String money)
            throws AppException {
        if (money != null && money.trim().length() > 0
                && money.trim().matches("(-)?\\d+(\\.\\d{1,2})?"))
        {
            String sign = "";
            if (money.startsWith("-"))
            {
                sign = "-";
                money = money.substring(1, money.length());
            }
            money = money.trim();
            String tmp = "";
            int posOfDot = money.indexOf(".");
            if (posOfDot > 0)
            {
                String sub = money.substring(posOfDot, money.length());
                if (sub.length() < 3)
                {
                    sub += "0";
                }
                money = money.substring(0, posOfDot);
                if (money.length() > 3)
                {
                    tmp = money.substring(money.length() - 3, money.length());
                    money = money.substring(0, money.length() - 3);
                    while (money.length() > 3)
                    {
                        tmp = money.substring(money.length() - 3, money
                                .length())
                                + "," + tmp;
                        money = money.substring(0, money.length() - 3);
                    }
                    return sign + money + "," + tmp + sub;
                } else
                {
                    return sign + money + sub;
                }

            } else
            {
                if (money.length() > 3)
                {
                    tmp = money.substring(money.length() - 3, money.length());
                    tmp += ".00";
                    money = money.substring(0, money.length() - 3);
                    while (money.length() > 3)
                    {
                        tmp = money.substring(money.length() - 3, money
                                .length())
                                + "," + tmp;
                        money = money.substring(0, money.length() - 3);
                    }
                    return sign + money + "," + tmp;
                } else
                {
                    return sign + money + ".00";
                }
            }
        } else
        {
            throw new AppException(
                    "");
        }
    }


    public static String fromMoneyFormat(String money)
            throws AppException {
        if (money != null && money.trim().length() > 0
                && Formater.isMoneyFormat(money.trim()))
        {
            return money.trim().replaceAll(",", "");
        } else
        {
            throw new AppException(
                    "");
        }
    }


    public static boolean isMoneyFormat(String money)
            throws AppException {
        if (money != null && money.trim().length() > 0)
        {
            return (money.trim().matches(
                    "(-)?(\\d{1,3},)?(\\d{3},)*(\\d{3})(\\.\\d{1,2})?") || money
                    .trim().matches("(-)?\\d{1,3}(\\.\\d{1,2})?"));
        } else
        {
            throw new AppException("");
        }
    }

    public static boolean isSimplyMoneyFormat(String money)
            throws AppException {
        if (money != null && money.trim().length() > 0)
        {
            return (money.trim().matches("(-)?\\d+(\\.\\d{1,2})?"));
        } else
        {
            throw new AppException("");
        }
    }

    public static boolean isSpaceOfString(String arg) {
        if (arg != null && arg.trim().length() > 0)
        {
            return false;
        }
        return true;
    }

    public static void main(String[] arg) throws Exception {
        String s = addDate("2006-1-1", 31);
    }

    public static String cutString(String str, int len) {
    	len = len -3;
    	if(StringUtil.isBlank(str))
    		return "";
        byte[] tmpByts = str.getBytes();
        if (len+3 > tmpByts.length)
            return str;
        	//len = tmpByts.length;
        int cnCount = 0;
        for (int i = 0; i < len; i++)
        {
            if (tmpByts[i] < 0)
                cnCount++;
        }
        if (cnCount % 2 == 1)
            len--;
        byte[] newByts = new byte[len];
        for (int i = 0; i < len; i++)
        {
            newByts[i] = tmpByts[i];
        }
        return new String(newByts) + "...";
    }

    public static String getAutoFileSize(int fileSize){
        
        DecimalFormat formater = new DecimalFormat();
        formater.applyPattern("###.##");
        if(fileSize < 1024){
            return fileSize + " B";
        }
        else if(fileSize < 1024*1024){
            return formater.format(fileSize/1024f) + " KB";
        }
        else if(fileSize < 1024*1024*1024){
            return formater.format(fileSize/(1024*1024f)) + " MB";
        }
        else{
            return formater.format(fileSize/(1024*1024*1024f)) + " GB";
        }
    }
}